import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Tag,
  Button,
  Space,
  Typography,
  Statistic,
  Row,
  Col,
  Modal,
  Alert,
  Tooltip,
  Empty,
  Divider
} from 'antd';
import {
  BugOutlined,
  WarningOutlined,
  InfoCircleOutlined,
  DeleteOutlined,
  DownloadOutlined,
  ReloadOutlined,
  EyeOutlined
} from '@ant-design/icons';
import errorMonitor from './errorMonitor';

const { Title, Text, Paragraph } = Typography;

/**
 * 错误监控面板组件
 */
const ErrorMonitorPanel = () => {
  const [errors, setErrors] = useState([]);
  const [stats, setStats] = useState({ total: 0, byType: {}, recent: [] });
  const [selectedError, setSelectedError] = useState(null);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [loading, setLoading] = useState(false);

  // 刷新错误数据
  const refreshData = () => {
    setLoading(true);
    try {
      const allErrors = errorMonitor.getErrors();
      const errorStats = errorMonitor.getErrorStats();
      
      setErrors(allErrors);
      setStats(errorStats);
    } catch (error) {
      console.error('刷新错误数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 组件挂载时加载数据
  useEffect(() => {
    refreshData();
    
    // 设置定时刷新
    const interval = setInterval(refreshData, 5000);
    
    return () => clearInterval(interval);
  }, []);

  // 清空错误
  const handleClearErrors = () => {
    Modal.confirm({
      title: '确认清空',
      content: '确定要清空所有错误记录吗？此操作不可恢复。',
      onOk: () => {
        errorMonitor.clearErrors();
        refreshData();
      }
    });
  };

  // 导出错误日志
  const handleExportErrors = () => {
    errorMonitor.exportErrors();
  };

  // 查看错误详情
  const handleViewDetail = (error) => {
    setSelectedError(error);
    setDetailModalVisible(true);
  };

  // 错误类型标签渲染
  const getErrorTypeTag = (type) => {
    const typeConfig = {
      javascript: { color: 'red', icon: <BugOutlined />, text: 'JS错误' },
      unhandledrejection: { color: 'orange', icon: <WarningOutlined />, text: 'Promise错误' },
      resource: { color: 'yellow', icon: <WarningOutlined />, text: '资源错误' },
      manual: { color: 'blue', icon: <InfoCircleOutlined />, text: '手动记录' },
      warning: { color: 'orange', icon: <WarningOutlined />, text: '警告' },
      info: { color: 'blue', icon: <InfoCircleOutlined />, text: '信息' },
      'console-warning': { color: 'orange', icon: <WarningOutlined />, text: '控制台警告' },
      'console-error': { color: 'red', icon: <BugOutlined />, text: '控制台错误' }
    };
    
    const config = typeConfig[type] || { color: 'default', icon: <InfoCircleOutlined />, text: type };
    
    return (
      <Tag color={config.color} icon={config.icon}>
        {config.text}
      </Tag>
    );
  };

  // 表格列定义
  const columns = [
    {
      title: '时间',
      dataIndex: 'timestamp',
      key: 'timestamp',
      width: 160,
      render: (timestamp) => (
        <Text style={{ fontSize: '12px' }}>
          {new Date(timestamp).toLocaleString()}
        </Text>
      )
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: 120,
      render: (type) => getErrorTypeTag(type)
    },
    {
      title: '错误信息',
      dataIndex: 'message',
      key: 'message',
      ellipsis: true,
      render: (message) => (
        <Tooltip title={message}>
          <Text style={{ fontSize: '13px' }}>{message}</Text>
        </Tooltip>
      )
    },
    {
      title: '位置',
      key: 'location',
      width: 150,
      render: (_, record) => {
        if (record.filename && record.lineno) {
          return (
            <Text style={{ fontSize: '12px' }}>
              {record.filename.split('/').pop()}:{record.lineno}
            </Text>
          );
        }
        return '-';
      }
    },
    {
      title: '操作',
      key: 'action',
      width: 80,
      render: (_, record) => (
        <Button
          type="link"
          size="small"
          icon={<EyeOutlined />}
          onClick={() => handleViewDetail(record)}
        >
          详情
        </Button>
      )
    }
  ];

  return (
    <div style={{ padding: '20px' }}>
      <Card>
        <div style={{ marginBottom: '20px' }}>
          <Row justify="space-between" align="middle">
            <Col>
              <Title level={4}>
                <BugOutlined /> 错误监控面板
              </Title>
            </Col>
            <Col>
              <Space>
                <Button 
                  icon={<ReloadOutlined />} 
                  onClick={refreshData}
                  loading={loading}
                >
                  刷新
                </Button>
                <Button 
                  icon={<DownloadOutlined />} 
                  onClick={handleExportErrors}
                  disabled={errors.length === 0}
                >
                  导出日志
                </Button>
                <Button 
                  danger 
                  icon={<DeleteOutlined />} 
                  onClick={handleClearErrors}
                  disabled={errors.length === 0}
                >
                  清空错误
                </Button>
              </Space>
            </Col>
          </Row>
        </div>

        {/* 统计信息 */}
        <Row gutter={16} style={{ marginBottom: '20px' }}>
          <Col span={6}>
            <Card size="small">
              <Statistic
                title="总错误数"
                value={stats.total}
                prefix={<BugOutlined />}
                valueStyle={{ color: stats.total > 0 ? '#cf1322' : '#52c41a' }}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card size="small">
              <Statistic
                title="JS错误"
                value={stats.byType.javascript || 0}
                prefix={<BugOutlined />}
                valueStyle={{ color: '#cf1322' }}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card size="small">
              <Statistic
                title="Promise错误"
                value={stats.byType.unhandledrejection || 0}
                prefix={<WarningOutlined />}
                valueStyle={{ color: '#fa8c16' }}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card size="small">
              <Statistic
                title="控制台警告"
                value={(stats.byType['console-warning'] || 0) + (stats.byType['console-error'] || 0)}
                prefix={<WarningOutlined />}
                valueStyle={{ color: '#fadb14' }}
              />
            </Card>
          </Col>
        </Row>

        {/* 错误列表 */}
        <Card title="错误列表" size="small">
          {errors.length === 0 ? (
            <Empty 
              description="暂无错误记录"
              image={Empty.PRESENTED_IMAGE_SIMPLE}
            />
          ) : (
            <Table
              columns={columns}
              dataSource={errors}
              rowKey="id"
              size="small"
              pagination={{
                pageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条记录`
              }}
              scroll={{ x: 800 }}
            />
          )}
        </Card>
      </Card>

      {/* 错误详情模态框 */}
      <Modal
        title="错误详情"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>
            关闭
          </Button>
        ]}
        width={800}
      >
        {selectedError && (
          <Space direction="vertical" style={{ width: '100%' }}>
            <Alert
              message={selectedError.message}
              type="error"
              showIcon
            />
            
            <Row gutter={16}>
              <Col span={12}>
                <Text strong>错误类型:</Text> {getErrorTypeTag(selectedError.type)}
              </Col>
              <Col span={12}>
                <Text strong>发生时间:</Text> {new Date(selectedError.timestamp).toLocaleString()}
              </Col>
            </Row>
            
            <Divider />
            
            {selectedError.filename && (
              <div>
                <Text strong>文件位置:</Text> {selectedError.filename}:{selectedError.lineno}:{selectedError.colno}
              </div>
            )}
            
            {selectedError.url && (
              <div>
                <Text strong>页面URL:</Text> {selectedError.url}
              </div>
            )}
            
            {selectedError.userAgent && (
              <div>
                <Text strong>用户代理:</Text> 
                <Paragraph style={{ fontSize: '12px', marginTop: '4px' }}>
                  {selectedError.userAgent}
                </Paragraph>
              </div>
            )}
            
            {selectedError.stack && (
              <div>
                <Text strong>错误堆栈:</Text>
                <Paragraph 
                  code 
                  style={{ 
                    background: '#f6f8fa', 
                    padding: '12px',
                    fontSize: '12px',
                    maxHeight: '300px',
                    overflow: 'auto',
                    marginTop: '8px'
                  }}
                >
                  {selectedError.stack}
                </Paragraph>
              </div>
            )}
            
            {selectedError.componentStack && (
              <div>
                <Text strong>组件堆栈:</Text>
                <Paragraph 
                  code 
                  style={{ 
                    background: '#f6f8fa', 
                    padding: '12px',
                    fontSize: '12px',
                    maxHeight: '200px',
                    overflow: 'auto',
                    marginTop: '8px'
                  }}
                >
                  {selectedError.componentStack}
                </Paragraph>
              </div>
            )}
          </Space>
        )}
      </Modal>
    </div>
  );
};

export default ErrorMonitorPanel;